import { cloneDeep } from 'lodash-es';
import { isArray } from './is';

/**
 * @description 数组随机排序
 * @author wfd
 * @date 2022/11/14 20:21
 * @example
 * @param arr
 * @returns {any}
 */
export const randArrSort = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    const iRand = parseInt(String(arr.length * Math.random()));
    const temp = arr[i];
    arr[i] = arr[iRand];
    arr[iRand] = temp;
  }
  return arr;
};

/**
 * @description 数组排序
 * @author wfd
 * @date 2022/11/14 20:21
 * @example
 * @param {string | Array<Numberish>} attr 排序根据的属性
 * @param {boolean} sortOrder 正序还是倒序
 * @returns {(a, b) => (number | number)}
 */
export function arrSort (attr: string | Array<Numberish>, sortOrder = true) {
  let _order;
  if (sortOrder) {
    _order = 1;
  } else {
    _order = sortOrder ? 1 : -1;
  }
  
  return function (a, b) {
    if (!isArray(attr)) {
      attr = [attr];
    }
    for (const item of attr) {
      a = a[item];
      b = b[item];
    }
    if (a < b) {
      return _order * -1;
    }
    if (a > b) {
      return _order * 1;
    }
    return 0;
  };
}

/**
 * @description 随机从数组中取出 num 个数组
 * @author wfd
 * @date 2022/1/13 14:12
 * @example
 * @param arrList
 * @param num
 */
export const makeRandomArr = <T = any> (arrList: T[], num = 1) => {
  const temp_array = cloneDeep(arrList);
  const return_array: T[] = [];
  for (let i = 0; i < num; i++) {
    if (temp_array.length > 0) {
      const arrIndex = Math.floor(Math.random() * temp_array.length);
      return_array[i] = temp_array[arrIndex];
      temp_array.splice(arrIndex, 1);
    } else {
      break;
    }
  }
  return return_array;
};
